/*============================================================================
 PROJECT: TalkWrench
 FILE:    BaseViewController.m
 AUTHOR:  Nguyen Minh Khoai
 DATE:    1/30/13
 =============================================================================*/

/*============================================================================
 IMPORT
 =============================================================================*/
#import "BaseViewController.h"
#import "UIBarButtonItem+Customizes.h"
#import "UIView+PopUp.h"
#import "DAKeyboardControl.h"

/*============================================================================
 PRIVATE MACRO
 =============================================================================*/
#define kLoadingViewWidth 80
#define kLoadingViewHeight 80

/*============================================================================
 PRIVATE INTERFACE
 =============================================================================*/

@interface BaseViewController ()
@property (nonatomic, strong)   UIActivityIndicatorView *loadingView;
@end

@implementation BaseViewController

@synthesize hiddenBackButton;
@synthesize titleLabel;
@synthesize titleLabelString;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)setUpNavigationBar {
    self.navigationBarButtonPadding = (IS_IPAD ? 10 : 0);
    self.hiddenRightButton = NO;
    
    if(!self.leftButtonImageName) {
        self.leftButtonImageName = @"btn_back";
    }
    
    /* Create back button on navigation bar */
    if (!self.navigationItem.hidesBackButton && !hiddenBackButton) {
        
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithTarget:self
                                                                                selector:@selector(didTouchedOnLeftButton:)
                                                                                   title:nil
                                                                                iconName:self.leftButtonImageName
                                                                          backgroundName:nil
                                                                                 padding:-self.navigationBarButtonPadding];
        
        if(self.hasBadgeView) {
            self.badgeView = [[JSBadgeView alloc] initWithParentView:self.navigationItem.leftBarButtonItem.customView
                                                           alignment:JSBadgeViewAlignmentTopRightOrigin];
            self.badgeView.badgeTextFont = FontOpenSanWithSize(IS_IPAD ? 20 : 12);
            self.badgeView.badgeSizeAdjustment = kBadgeAdjust;
            self.badgeView.badgePositionAdjustment = CGPointMake(-1, 7);
            
        }
    }
    
    if (!self.hiddenRightButton) {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTarget:self
                                                                                 selector:@selector(handleTouchedOnRightButton:)
                                                                                    title:self.rightButtonTitle
                                                                                 iconName:self.rightButtonImageName
                                                                           backgroundName:nil
                                                                                  padding:self.navigationBarButtonPadding];
    }
    
    /* init title */
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    titleLabel.font = FontOpenSansBoldWithSize(22);
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = MKTextAlignmentCenter;
    titleLabel.autoresizingMask = UIViewAutoresizingNone;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.text = titleLabelString;
    self.navigationItem.titleView = titleLabel;
}


- (void)awakeFromNib {
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /* setting navigation controller */
    [self setUpNavigationBar];
    
    @autoreleasepool {
        /* add pin to zoom view */
        if(self.enablePinToZoomAtPoint) {
            UIPinchGestureRecognizer *fingerPinch = [[UIPinchGestureRecognizer alloc]
                                                     initWithTarget:self
                                                     action:@selector(handleFingerPinch:)];
            
            [[self view] addGestureRecognizer:fingerPinch];
        }
    }
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    [self unregisterNotifications];
    [super viewDidUnload];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    if (SupportiOS7) {
        if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
            self.edgesForExtendedLayout = UIRectEdgeNone;
        
        CGRect viewBounds = self.view.bounds;
        CGFloat topBarOffset = self.topLayoutGuide.length;
        viewBounds.origin.y = topBarOffset * -1;
        
        self.view.bounds = viewBounds;
        self.navigationController.navigationBar.translucent = NO;
    }
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [self doLayout:toInterfaceOrientation];
}

- (void)dealloc {
    [self unregisterNotifications];
}

- (void)viewDidDisappear:(BOOL)animated {
    [self.view removeKeyboardControl];
    [self hideLoadingView];
    [super viewDidDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self registerNotifications];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateBadgeNumber];
}

/*----------------------------------------------------------------------------
 Method:      updateBadgeNumber
 -----------------------------------------------------------------------------*/
- (void)updateBadgeNumber {
    
    //    if(self.hasBadgeView) {
    //
    //        if (appDelegate.dataCenter.unreadNotificationCount + appDelegate.dataCenter.unreadMessageCount > 0) {
    //            self.badgeView.badgeText = [NSString stringWithFormat:@"%d", appDelegate.dataCenter.unreadNotificationCount + appDelegate.dataCenter.unreadMessageCount];
    //        }
    //        else{
    //            self.badgeView.badgeText = @"";
    //        }
    //
    //        __weak BaseViewController * weakSelf = self;
    //        [appDelegate.dataCenter getBadgeNumberUsingBlock:^(id data, id error) {
    //            if (!error) {
    //                int messagesCount = [[[data objectForKey:@"data"] objectForKey:@"unread_messages"] intValue];
    //                int notificatonsCount = [[[data objectForKey:@"data"] objectForKey:@"unread_notifications"] intValue];
    //                //                messagesCount = 1;
    //                //                notificatonsCount = 2;
    //                /*  save counters */
    //                appDelegate.dataCenter.unreadMessageCount = messagesCount;
    //                appDelegate.dataCenter.unreadNotificationCount = notificatonsCount;
    //
    //                if (notificatonsCount + messagesCount > 0) {
    //                    weakSelf.badgeView.badgeText = [NSString stringWithFormat:@"%d", messagesCount + notificatonsCount];
    //                }
    //                else{
    //                    weakSelf.badgeView.badgeText = @"";
    //                }
    //            }
    //        }];
    //    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Gesture Event

- (void)handleFingerPinch:(UIPinchGestureRecognizer *)gesture {
    NSLog(@"Pinch scale: %f", gesture.scale);
    CGAffineTransform transform = CGAffineTransformMakeScale(gesture.scale, gesture.scale);
    // you can implement any int/float value in context of what scale you want to zoom in or out
    
    self.view.transform = transform;
}

#pragma mark - UINavigationBar Button Events

- (void)didTouchedOnLeftButton:(id)sender {
    [self unregisterNotifications];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didTouchedOnRightButton:(id)sender {
    
}

- (void)handleTouchedOnRightButton:(id)sender{
    /* before touch on Right button, trick for disable touch */
    if (self.processing) {
        /* ingnore touching */
    }else {
        [self didTouchedOnRightButton:sender];
    }
    
}

#pragma mark - MBProgressHUB

- (void)showLoadingViewWithMessage:(NSString *)message {
    if(!_progressView) {
        
        CGFloat x = (self.view.bounds.size.width - kLoadingViewWidth)/2;
        CGFloat y = (self.view.bounds.size.height - kLoadingViewHeight)/2;
        CGRect rect = CGRectMake(x, y, kLoadingViewWidth, kLoadingViewHeight);
        
        
        self.progressView = [[ProgressView alloc] initWithFrame:rect];
        [_progressView setTextColor:[UIColor whiteColor]];
        [_progressView setActivityColor:[UIColor grayColor]];
        _progressView.activityView.center = CGPointMake(_progressView.frame.size.width/2, _progressView.frame.size.height/2);
        _progressView.backgroundColor = [UIColor clearColor];
        [_progressView setBackgroundImage:nil];
    }
    
    [_progressView setTitle:message];
    [_progressView bringSubviewToFront:self.view];
    [_progressView showOnView:self.view animation:YES freeze:YES top:IS_IPAD ? self.customNavigationBar.frame.size.height : 0];
}

- (void)showLoadingView {
    [self showLoadingViewWithMessage:@""];
    self.processing = YES;
}

- (void)hideLoadingView {
    [_progressView performSelector:@selector(hide) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES];
    self.processing = NO;
}

- (void)doLayout:(UIInterfaceOrientation)orientation {
    
}

- (BOOL)validateField:(UIView *)field {
    return YES;
}

- (BOOL)doValidation {
    return YES;
}

- (void)registerNotifications {
    
}

- (void)unregisterNotifications {
    NotifUnregAll(self);
}

@end
